import React, { PureComponent } from 'react';
import DocumentTitle from 'react-document-title';
import { withRouter, Prompt } from 'react-router-dom'

import { SubmitStyle } from './style'
import { Button, Modal, Toast } from 'antd-mobile'

import request from '@service'
import axios from 'axios'
import { store } from '@store'
import { selectedAddressAction, updateOrder } from '@store/actionCreators'

import { OrderGoodsItem } from '@common/goodsItem'
import { Address, PriceDetail, TuanZhangAddress, Loadage, AcceptableTime, HDYProvision, Remark } from './components';
import { getGroupFirstAddress, detactGroupIsFull } from '@api/submit'

// const  evn =  process.env.NODE_ENV === 'development' ? false : true

const alert = Modal.alert


class Submit extends PureComponent {
  state = {
    orderDetail: {},
    orderno: '',
    acceptableTime: '24',
    agree: true,
    seeProvision: false,
    payLoading: false
  }
  paying = false

  uniacid = store.getState().appConfig.uniacid

  orderno = this.props.match.params.caigouOrderId

  componentDidMount() {
    const { caigouOrderId, tuanid } = this.props.match.params

    const fullLoad = localStorage.getItem('fullLoad') // 满载

    console.log('是否满载', fullLoad)

    let getCaigouInfo = {
      data: {
        action: 'payment_show',
        deposit_orderno: caigouOrderId,
        tuan_id: tuanid
      }
    }

    axios.all([getGroupFirstAddress({ tuan_id: tuanid }), request(getCaigouInfo)]).then(
      axios.spread((groupAddress, res) => {

        if (groupAddress.status === 200) {
          if (res.status === 200) {
            this.setState({
              groupFirstAddress: groupAddress.data,
              orderDetail: res.data,
              sfje: res.data.sfje,
              orderno: res.data.deposit_orderno,
              tuanid: parseInt(tuanid),
              fullLoad,
            }, () => {
              store.dispatch(updateOrder(Object.assign({}, store.getState().order, { orderno: res.data.deposit_orderno }))) // 缓存当前订单
            })
          } else {
            Toast.info('网络错误', 1)
          }
        } else {
          Toast.info('网络错误', 1)
        }

      })
    )
  }

  componentWillUnmount() {
    store.dispatch(selectedAddressAction({})) // 清除 选择地址
  }


  render() {

    const { orderDetail, tuanid, groupFirstAddress, fullLoad, payLoading } = this.state


    return (
      <>
        <DocumentTitle title={this.props.route.title} />

        <Prompt
          message={(location, action) => {
            let el = document.getElementsByClassName('am-modal-wrap')
            if (el.length === 0) {
              return true
            } else {
              Toast.info('请先关闭弹窗')
              return false
            }
          }} when={true}

        />


        <div style={{ backgroundColor: '#F5F5F5', height: '100%' }}>

          <SubmitStyle>

            {

              orderDetail?.good &&

              <div style={{ overflow: "scroll", height: 'calc(100vh - 1.48rem)' }}>

                <div style={{ margin: '.14rem .32rem' }}>
                  <Address data={orderDetail.address} orderno={this.orderno} />
                  {tuanid !== 0 && <TuanZhangAddress groupFirstAddress={groupFirstAddress} />}
                  <OrderGoodsItem marginStyle={{ marginTop: '.13rem', padding: '.32rem 0' }} className="single-goods"
                    goods={orderDetail.good} />
                  <PriceDetail priceList={orderDetail.priceList} />

                  {/*  fullLoad true, 满载不再需要设置 下面两个选项 */}
                  {tuanid === 0 && !fullLoad && <AcceptableTime />}
                  {tuanid === 0 && !fullLoad && <Loadage />}
                  <Remark />
                  <HDYProvision />
                </div>
              </div>
            }

            <div className="confirm-pay flex-row">
              <div className="pay-price">
                <span>您需要支付：</span>
                <span>￥{orderDetail.priceList && this.state.sfje}</span>
              </div>
              <Button
                className="pay-button"
                onClick={e => {
                  this.pay()
                }}
                loading={payLoading}
                disabled={payLoading}
              >
                提交订单
              </Button>
            </div>

          </SubmitStyle>

        </div>

      </>
    );
  }

  acceptableTime(val) {
    this.setState({
      acceptableTime: val,
    })
  }

  handelAgree() {
    this.setState({
      agree: !this.state.agree
    })
  }


  async pay() {
    // 支付 => 提交订单 4/16
    // 地址id
    const order = store.getState().order
    let { acceptableTime: actime, isRead, loadage, remark, agree } = order

    const addressid = store.getState().selectedAddress.id ? store.getState().selectedAddress.id : store.getState().defaultAddress.id;
    const selectedAddress = store.getState().selectedAddress
    const defaultAddress = store.getState().defaultAddress
    const { orderno, tuanid, groupFirstAddress, fullLoad, sfje: realPrice } = this.state
    const { needprepayratio, needprepayprice, good } = this.state.orderDetail
    const { isApplet } = store.getState().appConfig


    console.log(needprepayprice, 'sfje', realPrice, good)
    if (fullLoad) { // 如果满载
      actime = 0;
      loadage = 100;
    }

    if (tuanid !== 0) {

      let stock = await detactGroupIsFull({ tuan_id: tuanid })
      console.log('库存', stock)

      if (stock.status === 200) {
        let haveNum = parseInt(stock.data)
        let needNum = parseInt(good.num)
        if (needNum > haveNum) {
          Toast.info('所购数量超出现有库存', 2)
          return
        } else {

        }

      } else {
        Toast.info('未知错误(1004)', 1)
        return
      }


      if (selectedAddress.cityc) {
        if (selectedAddress.cityc !== groupFirstAddress.city) {
          alert('', <p
            style={{
              color: '#474747',
              fontSize: '.32rem',
              fontWeight: '500'
            }}
          >
            {/* 您的收货地址与,团长到货地址不匹配，请选择与团长到货地址匹配的地址，或选择与你期望地址匹配的团
            <br/> */}
            您的地址与该订单不匹配,请选择同城的拼单，或自己发起拼单
          </p>, [
            { text: '我知道了' }
          ])

          return
        }
      } else if (defaultAddress.cityc) {
        if (defaultAddress.cityc !== groupFirstAddress.city) {
          alert('', <p
            style={{
              color: '#474747',
              fontSize: '.32rem',
              fontWeight: '500'
            }}
          >
            您的地址与该订单不匹配,请重新选择同城拼单，或自己发起拼单
          </p>, [
            { text: '我知道了' }
          ])
          return
        }
      } else {
        Toast.info('默认地址，选择地址两者都存在')
      }

    }

    if (tuanid === 0 && !fullLoad) {
      if (!actime) {
        Toast.info('请填写拼单有效时间', 1)
        return
      }
      if (!loadage) {
        Toast.info('请选择允许装载量', 1)
        return
      }
    }


    if (agree === false) {
      Toast.info('请勾选同意 保证金规则', 1)
      return
    } else if (isRead === false) {
      Toast.info('请阅读条款并点击我已阅读', 1)
      return
    } else {
      if (addressid) {
        // 提交订单跳转到支付方式
        console.log(store.getState().order, this.order) // 为什么 this.order 不同步  闭包？
        store.dispatch(updateOrder(Object.assign({}, store.getState().order, {
          orderno,
          needprepayratio,
          needprepayprice,
          tuanid,
          realPrice,
          good
        }))) // 缓存当前订单
        const info = {
          data: {
            allowed_lasttime: actime,
            loadage: loadage,
            remarks: remark,
            deposit_orderno: orderno,
            addressid,
            action: 'update_order_info'
          }
        }
        this.setState({
          payLoading: true
        }, () => {
          request(info).then(res => { // 提交订单
            if (res.status === 200) {
              isApplet ? window.navigateToWebWiew(`/payway/${orderno}`) : this.props.history.push(`/payway/${orderno}`)
            } else if (res.status === 400) {
              Toast.info(res.msg, 2)
              this.setState({
                payLoading: false
              })
            } else {
              Toast.info('提交订单错误', 2)
            }
          })
        })
      } else {
        Toast.info('请选择地址', 1)
      }
    }
  }
}


export default withRouter(Submit);